/*
 * @Descripttion: 
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2023-03-13 10:50:39
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2024-02-07 16:41:03
 */
import { useEffect, useReducer, useRef, useState } from 'react';
import { View, Button, useWindowDimensions, StyleSheet, TouchableOpacity, Pressable } from 'react-native'
import { actions, getContentCSS, RichEditor, RichToolbar } from 'react-native-pell-rich-editor';
import { WebView } from 'react-native-webview'
import Request from '../../utils/Request';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5'
import { HStack, Spinner, useColorModeValue, useToast, Text, Box } from 'native-base';
import appColor from '../../utils/appColor';


function DetailScreen({ navigation, route }) {

  useEffect(() => {
    navigation.setOptions({ title: route.params.name })
  }, [])

  const [loading, setLoading] = useState(true)

  const window = useWindowDimensions()

  const [initHTML, setInitHTML] = useState('<p>加载中...</p>')
  const richText = useRef(null)

  useEffect(() => {
    const { siteid, plateid } = route.params
    const url = encodeURIComponent(encodeURIComponent(route.params.contentUrl))
    Request.get(`/content/detail/${siteid}/${plateid}/${url}`).then(data => {
      setInitHTML(`${data.data}<div style="height: 100px"></div>`)
      richText.current?.setContentHTML(`${data.data}<div style="height: 100px"></div>`)
      setLoading(false)
    })
  }, [])


  const editorInitializedCallback = () => {
    console.log('init finish !')
  }

  const Toast = useToast()
  const download = async () => {
    let data = {
      url: route.params.downUrl,
      title: route.params.title,
      description: route.params.name
    }
    btnDispatch({ type: 'download' })
    let res = await Request.post('/content/download', data)

    Toast.show({ title: res.message, duration: 2000, placement: 'top' })
    btnDispatch({ type: 'download' })

  }

  const btnReducer = (state, action) => {
    let newState = { ...state }
    switch (action.type) {
      case 'download':
        newState.downLoading = !newState.downLoading
        return newState
      case 'store':
        newState.downLoading = !newState.downLoading
        return newState
      case 'rss':
        newState.rssLoading = !newState.rssLoading
        return newState
      default:
    }
  }
  const [btnState, btnDispatch] = useReducer(btnReducer, { storeLoading: false, downLoading: false, rssLoading: false })

  const btnBg = useColorModeValue(appColor.lightPopbg, appColor.darkPopbg)
  const pressedBtnbg = useColorModeValue(appColor.lightPopItembg, appColor.darkPopItembg)
  const btnStyle = ({ pressed }) => [styles.btn, { backgroundColor: pressed ? pressedBtnbg : btnBg }]

  const editorStyle = useColorModeValue({
    backgroundColor: appColor.lightbg,
    color: appColor.dark3,
  }, {
    backgroundColor: appColor.darkbg,
    color: appColor.light3,
  })

  const pageBg = useColorModeValue(appColor.lightbg, appColor.darkbg)

  return (
    <Box w={'100%'} h={'100%'} bgColor={pageBg}>
      {
        loading ? (
          <HStack h={'100%'} space={3} justifyContent={'center'} alignItems="center">
            <Spinner size="lg" color={'warning.500'} />
          </HStack>
        ) :
          (
            <>
              <RichEditor
                disabled={true}
                ref={richText}
                style={styles.rich}
                useContainer={false}
                editorStyle={editorStyle}
                initialHeight={window.height - 100}
                enterKeyHint={'done'}
                placeholder={'please input content'}
                initialContentHTML={initHTML}
                javaScriptEnabled={false}
                editorInitializedCallback={editorInitializedCallback}
              />

              <View style={styles.controlBtn}>
                <Pressable style={btnStyle}>
                  <FontAwesome5 name={'star'} size={22} brand color={'#f67a7a'} />
                  <Text>收藏</Text>
                </Pressable>
                <Pressable style={btnStyle} onPress={download} disabled={btnState.downLoading}>
                  {btnState.downLoading ?
                    <Spinner size='sm' color={'warning.500'} /> :
                    <FontAwesome5 name={'cloud-download-alt'} size={22} color={'#f67a7a'} />}
                  <Text>下载</Text>
                </Pressable>
                <Pressable style={btnStyle}>
                  <FontAwesome5 name={'rss'} size={22} brand color={'#f67a7a'} />
                  <Text>订阅</Text>
                </Pressable>
              </View>
            </>

          )
      }





      {/* 
        原始webview配置项
        <WebView
        originWhitelist={['*']}
        source={{ html: initHTML }}
        useWebKit={true}
        scrollEnabled={false}
        automaticallyAdjustContentInsets={true}
        hideKeyboardAccessoryView={true}
        keyboardDisplayRequiresUserAction={false}
        nestedScrollEnabled={!true}
        style={{ backgroundColor: "transparent", width: window.width }}
        dataDetectorTypes={'none'}
        domStorageEnabled={false}
        bounces={false}
        javaScriptEnabled={false}
      // onLoad={that.init}
      ></WebView> */}
    </Box>
  )
}

const styles = StyleSheet.create({
  rich: {
    backgroundColor: 'transparent'
  },
  controlBtn: {
    flexDirection: 'row',
    justifyContent: 'center',
    paddingHorizontal: 50,
    position: 'absolute',
    width: '100%',
    // backgroundColor: 'red',
    bottom: 30
  },
  btn: {
    alignItems: "center",
    borderRadius: 5,
    paddingHorizontal: 15,
    paddingVertical: 4,
    marginHorizontal: 20,
    elevation: 3.5
  }
})

export default DetailScreen